# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : ChatRobot.py
# @Author: Allister.Liu
# @Date  : 2018/3/22
# @Desc  : 微信机器人

import itchat
from itchat import content as con
import requests


"""
    微信智能机器人客服：
        功能：
            1、快速回复好友消息，可优化词库
            2、回复指定群聊消息，可以指定allow_chatrooms.data文件，一行一个群聊名称。
"""

KEY = "你自己申请的apikey"


def get_tuling_msg(msg):
    """
    获取机器人回复
    :param msg:
    :return:
    """
    if len(msg.strip()) < 1:
        return "空消息"
    try:
        api_url = "http://www.tuling123.com/openapi/api"
        data = {
            'key': KEY,
            'info': msg,
            'userid': 'Allister-Robot',
        }
        respose = requests.post(api_url, data=data)
        return respose.json()
    except Exception as e:
        print("获取机器人消息异常：%s" % e)
        return None


# 处理文本类消息
# 包括文本、位置、名片、通知、分享
@itchat.msg_register([con.TEXT, con.CARD, con.MAP, con.NOTE, con.SHARING])
def get_content(msg):
    print(msg['Text'])
    return get_tuling_msg(msg['Text']).get("text")


# 处理多媒体类消息
# 包括图片、录音、文件、视频
@itchat.msg_register([con.PICTURE, con.RECORDING, con.ATTACHMENT, con.VIDEO])
def get_files(msg):
    msg.download(msg.fileName)
    typeSymbol = {
        con.PICTURE: 'img',
        con.VIDEO: 'vid',
    }.get(msg.type, 'fil')
    print(msg)
    return '@%s@%s' % (typeSymbol, msg.fileName)


# # 处理好友添加请求
@itchat.msg_register(con.FRIENDS)
def add_friend(msg):
    msg.user.verify()
    msg.user.send('Nice to meet you!')


ALLOW_list = ()


def add_allow_list():
    lists = []
    with open("allow_chatrooms.data", 'r+', encoding='utf-8') as f:
        for line in f:
            lists.append(line.replace("\n", ""))
        global ALLOW_list
        ALLOW_list = tuple(lists)


text_list = (
    "Card",
    "Text",
    "Note",
    "Map",
    "Sharing"
)


# 群聊机器人开关  默认：开启=False
CLOSE_STATUS = False


def auth(nickName):
    """
    检查群聊是否在服务范围之内
    :param uid:
    :return:
    """
    if len(nickName.strip()) > 0 and ALLOW_list.count(nickName) > 0:
        return True
    else:
        return False


def room_owner_check(msg):
    """
    校验是否是群主
    :param msg:
    :return:
    """
    if msg.get('User').get('ChatRoomOwner') == msg.get('ActualUserName'):
        return True
    return False


# 处理群聊消息
@itchat.msg_register([con.TEXT, con.CARD, con.MAP, con.NOTE, con.SHARING, con.PICTURE, \
                      con.RECORDING, con.ATTACHMENT, con.VIDEO], isGroupChat=True)
def text_reply(msg):
    """
    回复群聊消息
    :param msg:
    :return:
    """
    print(msg)
    print(msg.get('User').get('NickName'))

    if room_owner_check(msg):
        if msg['Content'] == "机器人关闭":
            global CLOSE_STATUS
            CLOSE_STATUS = True
        elif msg['Content'] == "机器人开启":
            global CLOSE_STATUS
            CLOSE_STATUS = False

    if not CLOSE_STATUS:

        if auth(msg.get('User').get('NickName')) and not msg['isAt']:
            if text_list.count(msg['Type']) > 0:
                itchat.send(u'@%s\u2005 : %s' % (msg['ActualNickName'], get_tuling_msg(msg['Content']).get('text')), msg['FromUserName'])
            else:
                get_files(msg)

add_allow_list()
itchat.auto_login(hotReload=True)
itchat.run(True)


